package com.fh.controller.hydropower;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.fh.entity.system.TreeNode;
import com.fh.entity.system.User;
import com.fh.service.building.BuildingService;
import com.fh.service.building.FloorService;
import com.fh.service.building.RecordService;
import com.fh.service.business.BusinessService;
import com.fh.service.dictionary.DictionaryService;
import com.fh.service.hydropower.HydropowerDetailService;
import com.fh.service.hydropower.HydropowerPriceService;
import com.fh.service.hydropower.HydropowerService;
import com.fh.util.*;
import net.sf.json.JSONArray;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.system.Menu;
import com.fh.entity.Page;

/**
 * 类名称：HydropowerController
 * 创建人：FH
 * 创建时间：2017-09-28
 */
@Controller
@RequestMapping(value = "/hydropower")
public class HydropowerController extends BaseController {

    @Resource(name = "hydropowerService")
    private HydropowerService hydropowerService;
    @Resource(name = "hydropowerPriceService")
    private HydropowerPriceService hydropowerPriceService;
    @Resource(name = "buildingService")
    private BuildingService buildingService;
    @Resource(name = "businessService")
    private BusinessService businessService;
    @Resource(name = "dictionaryService")
    private DictionaryService dictionaryService;
    @Resource(name = "floorService")
    private FloorService floorService;
    @Resource(name = "hydropowerDetailService")
    private HydropowerDetailService hydropowerDetailService;
    @Resource(name = "recordService")
    private RecordService recordService;

    /**
     * 新增
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {
        logBefore(logger, "新增Hydropower");
        PageData res = new PageData();
        PageData pd = new PageData();

        User user = this.getSessionUser();
        try {
            pd = this.getPageData();
            String t = pd.getString("t");
            String type = "";
            if (StringHelper.isNotEmpty(t) && t.equals("0")) {
                type = CodeConstants.HYDROPOWER_ELECTRIC;
            } else {
                type = CodeConstants.HYDROPOWER_WATER;
            }
            String status = pd.getString("pid");
            if (StringHelper.isEmpty(status)) {
                pd.put("pid", 0);
            }
            pd.put("id", this.get32UUID());    //主键
            pd.put("isDel", 0); //是否删除
            pd.put("sort", 0); //排序
            pd.put("createId", user.getUSER_ID()); //创建时间
            pd.put("createDate", new DateUtil().getTime()); //创建时间
            pd.put("type", type);
            pd.put("isNew", 1);
            hydropowerService.save(pd);

            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","新增水电表");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);

            res.put("data", "");
            res.put("errcode", "00");
            res.put("errmsg", "操作成功");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "01");
            res.put("errmsg", "操作失败");
        }

        return res;
    }

    /**
     * 获取楼宇信息
     *
     * @return
     */
    @RequestMapping(value = "/getbuildings")
    @ResponseBody
    public Object getBuildings() {
        logBefore(logger, "获取楼宇信息");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            List<PageData> business = businessService.getBusiness(pd);
            if (business.size() > 0) {
                for (PageData bs : business) {
                    pd.put("businessId", bs.getString("ID"));
                    bs.put("childs", buildingService.getBuildings(pd));
                }
            }
            resultPd.put("data", business);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }


    /**
     * 获取水电表信息
     *
     * @return
     */
    @RequestMapping(value = "/findbypid")
    @ResponseBody
    public Object findByPid() {
        logBefore(logger, "获取水电表信息");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            pd.put("pid", "0");
            List<PageData> list = hydropowerService.findByPid(pd);
            List<TreeNode> nodeList = new ArrayList<TreeNode>();
            for (PageData parent : list) {
                TreeNode node = hydropowerService.recursiveTree(parent.getString("ID"), pd);
                nodeList.add(node);
            }
            resultPd.put("data", nodeList);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/findbyidfor")
    @ResponseBody
    public Object findByIdFor() {
        logBefore(logger, "获取水电表信息");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            pd = hydropowerService.findByIdFor(pd);
            resultPd.put("data", pd);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/findTreeTable")
    @ResponseBody
    public Object findTreeTable() {
        logBefore(logger, "获取水电表信息");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            List<PageData> list = hydropowerService.findTreeTable(pd);
            resultPd.put("data", JSONArray.fromObject(list));
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/findbyidforedit")
    @ResponseBody
    public Object findByIdForEdit() {
        logBefore(logger, "获取水电表信息");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            pd = hydropowerService.findByIdForEdit(pd);
            resultPd.put("data", pd);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    public void delete(PrintWriter out) {
        logBefore(logger, "删除Hydropower");
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            hydropowerService.delete(pd);
            out.write("success");
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }

    /**
     * 修改
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() throws Exception {
        logBefore(logger, "新增Hydropower");
        PageData res = new PageData();
        PageData pd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            hydropowerService.edit(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改水电表");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);

            res.put("data", "");
            res.put("errcode", "00");
            res.put("errmsg", "操作成功");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "01");
            res.put("errmsg", "操作失败");
        }

        return res;
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public PageData Del() throws Exception {
        logBefore(logger, "删除Hydropower");
        PageData res = new PageData();
        PageData pd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            hydropowerService.delete(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改水电表");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "00");
            res.put("errmsg", "操作成功");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "01");
            res.put("errmsg", "操作失败");
        }

        return res;
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(Page page) {
        logBefore(logger, "列表Hydropower");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            page.setPd(pd);
            List<PageData> varList = hydropowerService.list(page);    //列出Hydropower列表
            mv.setViewName("hydropower/hydropower/hydropower_list");
            mv.addObject("varList", varList);
            mv.addObject("pd", pd);
            mv.addObject(Const.SESSION_QX, this.getHC());    //按钮权限
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去新增页面
     */
    @RequestMapping(value = "/goAdd")
    public ModelAndView goAdd() {
        logBefore(logger, "去新增Hydropower页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            mv.setViewName("hydropower/hydropower/hydropower_edit");
            mv.addObject("msg", "save");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去修改页面
     */
    @RequestMapping(value = "/goEdit")
    public ModelAndView goEdit() {
        logBefore(logger, "去修改Hydropower页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            pd = hydropowerService.findById(pd);    //根据ID读取
            mv.setViewName("hydropower/hydropower/hydropower_edit");
            mv.addObject("msg", "edit");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAll")
    @ResponseBody
    public Object deleteAll() {
        logBefore(logger, "批量删除Hydropower");
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String DATA_IDS = pd.getString("DATA_IDS");
            if (null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.split(",");
                hydropowerService.deleteAll(ArrayDATA_IDS);
                pd.put("msg", "ok");
            } else {
                pd.put("msg", "no");
            }
            pdList.add(pd);
            map.put("list", pdList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 查询水电表默认值根据楼宇ID
     */
    @RequestMapping(value = "/getBuildingHydropowerPrice")
    @ResponseBody
    public PageData getBuildingHydropowerPrice() {
        logBefore(logger, "查询水电表默认值根据楼宇ID");
        PageData res = new PageData();
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            List<PageData> list = hydropowerPriceService.getBuildingHydropowerPrice(pd);
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel() {
        logBefore(logger, "导出Hydropower到excel");
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("CREATE_ID");    //1
            titles.add("CREATE_DATE");    //2
            titles.add("SORT");    //3
            titles.add("IS_DEL");    //4
            titles.add("TYPE");    //5
            titles.add("CODE");    //6
            titles.add("NAME");    //7
            titles.add("PID");    //8
            titles.add("LAST_DEGREES");    //9
            titles.add("LAST_DATE");    //10
            titles.add("CUR_DEGREES");    //11
            titles.add("CUR_DATE");    //12
            titles.add("ROOMID");    //13
            dataMap.put("titles", titles);
            List<PageData> varOList = hydropowerService.listAll(pd);
            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < varOList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", varOList.get(i).getString("CREATE_ID"));    //1
                vpd.put("var2", varOList.get(i).getString("CREATE_DATE"));    //2
                vpd.put("var3", varOList.get(i).getString("SORT"));    //3
                vpd.put("var4", varOList.get(i).getString("IS_DEL"));    //4
                vpd.put("var5", varOList.get(i).getString("TYPE"));    //5
                vpd.put("var6", varOList.get(i).getString("CODE"));    //6
                vpd.put("var7", varOList.get(i).getString("NAME"));    //7
                vpd.put("var8", varOList.get(i).getString("PID"));    //8
                vpd.put("var9", varOList.get(i).getString("LAST_DEGREES"));    //9
                vpd.put("var10", varOList.get(i).getString("LAST_DATE"));    //10
                vpd.put("var11", varOList.get(i).getString("CUR_DEGREES"));    //11
                vpd.put("var12", varOList.get(i).getString("CUR_DATE"));    //12
                vpd.put("var13", varOList.get(i).getString("ROOMID"));    //13
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /* ===============================权限================================== */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
    /* ===============================权限================================== */

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }


    @RequestMapping(value = "/editList")
    @ResponseBody
    public Object editList() {
        logBefore(logger, "获取水电表信息");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            PageData pd1 = new PageData();
            pd1.put("isNew", 0);
            pd1.put("id", "0605435bbf9b4a02ab460e58adeb7a0f");
            PageData pd2 = new PageData();
            pd2.put("isNew", 0);
            pd2.put("id", "49f7b2cd2ed64a7194e152f5ccfc3b1c");
            PageData pd3 = new PageData();
            pd3.put("isNew", 0);
            pd3.put("id", "1f2bfa1cd13d42149d110d9b48a7e64a");
            List<PageData> list = new ArrayList<>();
            list.add(pd1);
            list.add(pd2);
            list.add(pd3);
            hydropowerService.editList(list);
            resultPd.put("data", pd);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/findtype")
    @ResponseBody
    public Object findType() {
        logBefore(logger, "获取类型");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        User user = this.getSessionUser();
        try {
            pd = this.getPageData();
            pd.put("code", "PRO_009");
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> types = dictionaryService.findByCode(pd);
            List<PageData> floors = floorService.findByBuildingId(pd);
            JSONArray array = hydropowerService.getArray(floors, types);
            resultPd.put("data", array);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/findproject")
    @ResponseBody
    public Object findProject() {
        logBefore(logger, "获取项目");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            List<PageData> list = hydropowerService.findProject(pd);
            resultPd.put("data", list);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    @RequestMapping(value = "/findforchange")
    @ResponseBody
    public Object findForChange() {
        logBefore(logger, "换表获取数据");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            pd = hydropowerService.findForChange(pd);
            resultPd.put("data", pd);
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "01");
            resultPd.put("errmsg", "获取失败");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/change")
    @ResponseBody
    public PageData change() throws Exception {
        logBefore(logger, "更换水电表");
        PageData res = new PageData();
        PageData pd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            hydropowerService.edit(pd);
            PageData detail = new PageData();
            detail.put("id", pd.getString("did"));
            if (pd.getString("tp").equals("0")) {
                detail.put("curDegrees", pd.getString("newCounts"));
            } else {
                detail.put("lastDegrees", pd.getString("newCounts"));
            }
            hydropowerDetailService.edit(detail);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","更换水电表");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "00");
            res.put("errmsg", "操作成功");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "01");
            res.put("errmsg", "操作失败");
        }

        return res;
    }

    @RequestMapping(value = "/waterTabel")
    public ModelAndView waterTabel() {
        logBefore(logger, "水电表设置页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            PageData price = hydropowerPriceService.findBybuildingId(pd);
            if (pd.containsKey("type") && pd.getString("type").equals("b938139a48ed4344a11a7180b48eede6")) {
                pd.put("addType", 0);
                pd.put("addTips", "添加电表");
                pd.put("title","电表默认单价设置:");
                pd.put("tips","请输入电表默认价");
                if (price != null && price.containsKey("ELETRIC_PRICE")) {
                    pd.put("price", price.getString("ELETRIC_PRICE"));
                }
            } else {
                pd.put("addType", 1);
                pd.put("addTips", "添加水表");
                pd.put("title","水表默认单价设置:");
                pd.put("tips","请输入水表默认价");
                if (price != null && price.containsKey("WATER_PRICE")) {
                    pd.put("price", price.getString("WATER_PRICE"));
                }
            }
            if (price != null && price.containsKey("ID")) {
                pd.put("priceId", price.getString("ID"));
            }
            mv.setViewName("/hydropower/water_table");
            mv.addObject("pd", pd);
            mv.addObject(Const.SESSION_QX, this.getHC());    //按钮权限
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }
}
